var session_ws = null;

receiveMessage = (() => { })

function save_session() { // 保存会话
    if (session_ws == null || session_ws.readyState != 1) {
        return
    }
    console.log("==> Save session")
    session_info = []
    for (let key in win_wininfo) {
        // 生成会话信息
        var link_obj = document.getElementById("win_window-context-id-" + key.toString()).getElementsByTagName("iframe")[0];
        if (link_obj == undefined)
            link = ""
        else
            link = link_obj.contentWindow.location.href // 额外保存iframe链接信息
        session_info.push({
            "title": win_wininfo[key].title,
            "x": win_wininfo[key].x,
            "y": win_wininfo[key].y,
            "width": win_wininfo[key].width,
            "height": win_wininfo[key].height,
            "mode": win_wininfo[key].mode,
            "side": win_wininfo[key].side,
            "zindex": Number(document.getElementById("win_window-id-" + key.toString()).style.zIndex),
            "content": document.getElementById("win_window-context-id-" + key.toString()).innerHTML,
            "link": link,
            "data": win_windata[key]
        })
    }
    // 按照zindex离散化避免堆积
    session_info.sort((a, b) => {
        if (a.zindex < b.zindex) {
            return -1;
        }
        if (a.zindex > b.zindex) {
            return 1;
        }
        return 0;
    })

    // 保存
    session_ws.send(JSON.stringify(
        {
            "type": "save_session", "data": {
                "windows": session_info
            }
        }
    ));
}
function load_session(callback) { // 还原会话
    console.log("Loading session")
    var xhr = new XMLHttpRequest();
    xhr.open("GET", "/api/session/window", true);
    xhr.setRequestHeader("Content-Type", "application/json");
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4 && xhr.status == 200) {
            var json = JSON.parse(xhr.responseText);
            key = 0
            // 读取
            function next_win() {
                if (key >= json["windows"].length) {
                    setTimeout(() => {
                        setInterval(save_session, 5000);
                        callback() // 加载结束执行回调
                    }, 200)
                    return
                }
                win_create_window(json["windows"][key]["width"], json["windows"][key]["height"], json["windows"][key]["title"], json["windows"][key]["content"])
                win_windata[win_winid] = json["windows"][key]["data"]
                setTimeout(() => {
                    // 还原
                    (function (winid_now, nkey) {
                        win_wininfo[winid_now].functions.moveto(json["windows"][nkey]["x"], json["windows"][nkey]["y"])
                        setTimeout(() => {
                            if (json["windows"][nkey]["mode"] == 1) {
                                win_wininfo[winid_now].functions.max(json["windows"][nkey]["side"])
                            } else if (json["windows"][nkey]["mode"] == 2) {
                                win_wininfo[winid_now].functions.min()
                            }
                        }, 10)
                        if (json["windows"][nkey]["link"] != "") {
                            document.getElementById("win_window-context-id-" + key.toString()).getElementsByTagName("iframe")[0].contentWindow.location.href = json["windows"][nkey]["link"]
                        }
                    })(win_winid, key - 1)
                }, 10)
                key++;
                setTimeout(next_win, 30) // 使用timeout遍历并保证窗口完全创建
            }
            setTimeout(next_win, 0)
        }
    }
    xhr.send();
}

function connect_ws() { // ws重连
    setInterval(() => {
        if (session_ws == null || session_ws.readyState > 1) {
            session_ws = new WebSocket("/api/home/ws")
            session_ws.onmessage = receiveMessage
        }
    }, 1000)
}

connect_ws()

CHECK_DESKTOP_SESSION = 1